import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;

public class FileDecode {
    public static void main(String[] args) throws Exception {
        byte[] privateKeyBytes = readFromFile("./key/privateKey.pri");
        PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));

        // 解密文件并验证结果
        byte[] encryptedBytes = readFromFile("./test/1.txt");
        byte[] decryptedBytes = decryptUsingPrivateKey(encryptedBytes, privateKey);
        String decryptedText = new String(decryptedBytes, StandardCharsets.UTF_8);
        writeToFile("./test/2.txt", decryptedBytes);
        System.out.println("Decrypted text: " + decryptedText);
    }



    private static byte[] readFromFile(String fileName) throws Exception {
        try (FileInputStream inputStream = new FileInputStream(fileName)) {
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            return buffer;
        }
    }
    private static byte[] decryptUsingPrivateKey(byte[] encryptedBytes, PrivateKey privateKey)
            throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException,
            IllegalBlockSizeException, BadPaddingException {
        Cipher rsaCipher = Cipher.getInstance("RSA");
        rsaCipher.init(Cipher.DECRYPT_MODE, privateKey);
        return rsaCipher.doFinal(encryptedBytes);
    }
    private static void writeToFile(String fileName, byte[] content) throws IOException {
        try (FileOutputStream outputStream = new FileOutputStream(fileName)) {
            outputStream.write(content);
            outputStream.flush();
        }
    }
}
